from google.appengine.ext import db
import re

_PHONE_NUMBER_REGEX = re.compile(r'[^0-9]+')

class PhoneNumber(unicode):
  """
  >>> PhoneNumber('012-345-6789') == PhoneNumber('(012) 345-6789 ')
  True
  >>> PhoneNumber('012-345-6789') == PhoneNumber('(012) 345-6789 x100')
  False
  >>> PhoneNumber('012-345-6789') == u'0123456789'
  True
  >>> PhoneNumber('012-345-6789') == None
  False
  
  """
  @classmethod
  def clean(self, number):
    if number:
      return _PHONE_NUMBER_REGEX.sub('', number)
    else:
      return ''
  
  def __eq__(self, x):
    return PhoneNumber.clean(self) == PhoneNumber.clean(x)
  
  def __ne__(self, x):
    return not self.__eq__(x)
  
  def __repr__(self):
    return "PhoneNumber('%s')" % self

class PhoneNumberProperty(db.Property):
  """ Property for storing a phone number """
  data_type = PhoneNumber
  
  verbose_type = 'Phone Number'
  
  def get_value_for_datastore(self, model_instance):
    value = super(PhoneNumberProperty, self).\
      get_value_for_datastore(model_instance)
    if isinstance(value, PhoneNumber):
      return unicode(value)
    return value
    
  def get_value_for_lookup(self, model_instance):
    value = self.get_value_for_datastore(model_instance)
    if value:
      return PhoneNumber.clean(value)
  
  def get_value_for_sort(self, model_instance):
    return self.get_value_for_lookup(model_instance)
  
  def validate(self, value):
    if not value:
      return None
    return PhoneNumber(value)
  
  def make_value_from_datastore(self, value):
    if value is None:
      return None
    return PhoneNumber(value)
